<?php
declare (strict_types = 1);
namespace app\admin\model\user;

use app\admin\event\subscribes\user\Account as AccountSubscribe;
use app\common\model\BaseModel;
use app\school\model\school\School;
use think\facade\Event;
use think\model\concern\SoftDelete;

/**
 * 定义用户数据模型
 */
class Account extends BaseModel
{
    use SoftDelete;
    /**
     * 表名
     * @var string
     */
    protected $name = 'admin_user';

    /**
     * 设置自动写入时间
     * @var boolean
     */
    protected $autoWriteTimestamp = true;

    /**
     * 设置隐藏字段
     * @var array
     */
    protected $hidden = ['password', 'salt'];

    /**
     * 定义字段类型
     * @var array
     */
    protected $type = [
        'id'              => 'integer',
        'status'          => 'integer',
        'last_login_time' => 'timestamp',
        'delete_time'     => 'timestamp',
    ];

    /**
     * 定义表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 定义查询设备类型范围条件
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-19
     */
    public function scopeUpdateTime($query)
    {
        $query->order('update_time', 'DESC');
    }

    /**
     * 限制机构条件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-16
     * @param    [type]                         $query [description]
     * @return   [type]                                [description]
     */
    public function scopeMhm($query)
    {
        // 如果不是平台时, 加入机构条件限制
        if (!request()->is_platform) {
            $query->where('mhm_id', request()->mhm_id);
        }
    }

    /**
     * 排除超级管理员与自己
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-16
     * @param    [type]                         $query [description]
     * @return   [type]                                [description]
     */
    public function scopeExcludeAdmin($query)
    {
        $users = [
            1,
            request()->admin_user_id,
            app(School::class)->where('id', request()->user->getAttr('mhm_id'))->value('admin_user_id'),
        ];

        $query->whereNotIn('id', $users);
    }

    /**
     * 新增数据事件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-03
     * @return   string
     */
    public static function onBeforeInsert($user)
    {
        $user->status = 1;
        $user->mhm_id = $user->getAttr('mhm_id') ?: request()->user->getAttr('mhm_id');
    }

    /**
     * 成功创建之后
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-10
     * @param    [type]                         $user [description]
     * @return   [type]                               [description]
     */
    public static function onAfterInsert($user)
    {
        Event::subscribe(AccountSubscribe::class);
        Event::trigger('UserCreated',$user);
    }

    /**
     * 成功删除之后
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-10
     * @param    [type]                         $user [description]
     * @return   [type]                               [description]
     */
    public static function onAfterDelete($user)
    {
        Event::subscribe(AccountSubscribe::class);
        Event::trigger('UserDeleted', $user);
    }

    /**
     *  获取用户状态显示文字
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-03
     * @param string $value
     * @param $data
     * @return string
     */
    public function getStatusTextAttr($value = '', $data): string
    {
        return $data['status'] == 1 ? '正常' : '禁用';
    }

    public function getLastLoginIpAttr($value): string
    {
        return $value ?: '';
    }

    /**
     * 设置密码密钥
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-03
     */
    protected function setSaltAttr($value = '', $data): string
    {
        return 'pwd_' . mt_rand(100000, 999999);
    }

    /**
     * 加密密码
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-03
     */
    protected function setPasswordAttr($value = '', $data): string
    {
        // 触发设置密码密钥的方法
        $this->setAttr('salt', '');
        return $this->makePassword($value, $this->salt);
    }

    /**
     * 密码处理
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-10
     * @param    [type]                         $password [description]
     * @param    [type]                         $salt     [description]
     * @return   [type]                                   [description]
     */
    protected function makePassword($password, $salt): string
    {
        return md5(md5(strtolower($password)) . md5($salt));
    }

    /**
     * 设置状态查询条件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-10
     * @param    [type]                         $query  [description]
     * @param    integer                        $status 查询条件值
     */
    public function scopeStatus($query, $status = 1)
    {
        $query->where('status', $status);
    }

    /**
     * 是否为超级管理员
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-10
     * @return   boolean                        [description]
     */
    public function isSupperAdmin()
    {
        return $this->getAttr('id') === 1;
    }

    /**
     * 关联用户组绑定信息
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-17
     * @return   [type]                         [description]
     */
    public function groupAccess()
    {
        return $this->hasOne(GroupAccess::class, 'admin_user_id');
    }

    /**
     * 关联用户组绑定信息
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-17
     * @return   [type]                         [description]
     */
    public function groupIds()
    {
        return $this->hasOne(GroupAccess::class, 'admin_user_id')->bind(['group_ids' => 'admin_user_group_ids']);
    }
}
